package com.ling.pl.core.commons.springmvc;

/**
 * Created by bo.wang on 2016/9/27.
 */

import com.ling.pl.core.commons.springmvc.constant.FailStatus;
import com.ling.pl.core.commons.springmvc.constant.ResultStatus;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * ResponseBody包装类，返回Result
 */
public class ResponseBodyWrapHandler implements HandlerMethodReturnValueHandler {

    private final HandlerMethodReturnValueHandler delegate;

    public ResponseBodyWrapHandler(HandlerMethodReturnValueHandler delegate) {
        this.delegate = delegate;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return delegate.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        ResposeInfo<Object> result = new ResposeInfo<>();
        result.setSuccess(true);
        String returnType_ = returnType.getParameterType().toString();
        if (returnValue != null || (returnValue == null && ("void".equals(returnType_)))) {//||"class java.lang.String".equals(returnType_)
            result.setStatus(ResultStatus.SUCCESS);
            result.setData(returnValue);
        } else {
            result.setStatus(ResultStatus.FAIL);
            result.setErrorCode(FailStatus.NULLDATA);
//            result.setException("空数据");
            result.setMessage("空数据");
        }
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        result.setUrl(request.getRequestURI());
        delegate.handleReturnValue(result, returnType, mavContainer, webRequest);
    }
}